<script setup lang="ts">
const props = defineProps({
  dialogApi: {
    type: Object,
    required: true,
  },
  beforeSubmit: {
    type: Function,
    required: false,
  },
});

const dialog = reactive({
  title: "",
  visible: false,
  loading: false,
});
const emit = defineEmits(["updatePageData"]);

const rules = reactive({
  id: [{ required: true, message: "请输入", trigger: "blur" }],
});

const dataFormRef = ref();

let formData = ref<any>({});

function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      dialog.loading = true;
      const id = formData.value.id;
      if(props.beforeSubmit) props.beforeSubmit(formData.value)
      if (id) {
        props.dialogApi
          .update(id, formData.value)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            emit("updatePageData");
          })
          .finally(() => (dialog.loading = false));
      } else {
        props.dialogApi
          .add(formData.value)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            emit("updatePageData");
          })
          .finally(() => (dialog.loading = false));
      }
    }
  });
}

const open = (row?: any) => {
  if (row?.id) {
    dialog.title = "修改";
    props.dialogApi.getFormData(row.id).then((data: any) => {
      Object.assign(formData.value, data);
    });
  } else {
    formData.value = {};
    dialog.title = "新增";
  }
  dialog.visible = true;
};

defineExpose({
  open,
  handleSubmit,
});
</script>

<template>
  <!-- 分类表单弹窗 -->
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="500px"
    @close="handleCloseDialog"
  >
    <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
      <slot name="dialogFormContent" :formData="formData"></slot>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <slot name="extraButtons" :formData="formData"></slot>
        <el-button type="primary" @click="handleSubmit()">确定</el-button>
        <el-button @click="handleCloseDialog()">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
